<template>
  <van-form @submit="onSubmit">
    <van-field
        v-model="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"
        :placeholder="`请输入${editUser.editName}`"
    />
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import 'vant/es/toast/style';
import {useRoute, useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {ResponseResult} from "../models/resopnse";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import {userType} from "../models/user";

const route = useRoute()
const router = useRouter()

const editUser = ref<any>({
  editKey: route.query.editKey,
  currentValue: route.query.currentValue,
  editName: route.query.editName,
})

const onSubmit = async () => {
  // 获取用户信息
  const currentUser: userType | null = await getCurrentUser()
  if (!currentUser) {
    showFailToast('用户未登录')
    return
  }

  const res: ResponseResult<number> = await myAxios.post('user/update', {
    'id': currentUser.id,
    [editUser.value.editKey]: editUser.value.currentValue
  })
  console.log(res, '更新请求')
  if (res.code === 0 && res.data > 0) {
    showSuccessToast('修改成功')
    setTimeout(() => {
      router.back()
    }, 1000)
  } else {
    showFailToast('修改错误')
  }
};

</script>

<style scoped>

</style>
